﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WxApp.Helper;

namespace WxApp.Controllers
{
    [Produces("text/plain")]
    [Route("api/token")]
    public class TokenController : Controller
    {
        // GET: api/Token
        [HttpGet("valid")]
        public string Get(string signature, string timestamp, string nonce, string echostr)
        {
            var token = "wechat";
            string[] arrTmp = { token, timestamp, nonce };
            //字典排序
            Array.Sort(arrTmp);
            string tmpStr = string.Join("", arrTmp);
            //字符加密0
            var sha1 = HashSha1Sign(tmpStr);

            // logs
            RedisHelper.StringSet($"log_{DateTime.Now.ToString("yyyyMMddHHmmss")}", $"signature:{signature},timestamp:{timestamp},nonce:{nonce},echostr:{echostr},sha1:{sha1},token:{token}");

            return sha1.Equals(signature) ? echostr : string.Empty;
        }

        /// <summary>
        /// HMAC-SHA1加密算法
        /// </summary>
        /// <param name="str">加密字符串</param>
        /// <returns></returns>
        private string HashSha1Sign(string str)
        {
            var sha1 = SHA1.Create();
            var hash = sha1.ComputeHash(Encoding.GetEncoding("UTF-8").GetBytes(str));
            string byte2String = null;
            for (int i = 0; i < hash.Length; i++)
            {
                byte2String += hash[i].ToString("x2");
            }
            return byte2String;
        }
    }
}
